package com.xunsiya.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.xunsiya.common.config.util.Md5Util;
import com.xunsiya.service.system.CompanyService;
import com.xunsiya.service.system.RegisterService;
import com.xunsiya.service.system.UserService;
import com.xunsiya.system.vo.Company;
import com.xunsiya.system.vo.User;
import com.xunsiya.tools.common.msg.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * 注册控制层
 *
 * @author fw
 * @version 1.0
 *          <p/>
 *          <br/>
 *          <br/>修订人    修订时间      描述信息
 *          <br/>-----------------------------------------------------
 *          <br/>fw    2019/1/4    初始创建
 */
@RestController
@RequestMapping("/api/register")
public class RegisterController{
    @Autowired
    private UserService userService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private CompanyService companyService;
    @PostMapping("/regist")
    public Msg regist(@RequestBody User user)
            throws Exception {
        //校验企业名称
        String companyName = "";
        if(!"".equals(user.getCompanyName()))
        {
            companyName = user.getCompanyName();
        }
        else
        {
            companyName = "测试企业" + user.getUserName();
        }
        Company company = new Company();
        company.setCompanyName(companyName);
        company.setParentId(0);
        company.setContact(companyName);
        company.setEmail(user.getUserName());
        // 刚注册默认是没有激活状态
        user.setRealName(companyName + "管理员");
        user.setStatus(1);
        user.setEmail(user.getUserName());
        user.setCheckCode(Md5Util.getMd5("MD5", 0, null, user.getUserName()+user.getCreateTime()));
        // 注册用户
        if(userService.findUserByEmail(user.getEmail()) != null) {
            return new Msg(false, "注册失败，该用户已被注册!");
        }
        int result = companyService.registerCompany(company);
        if(result == -1)
        {
            return new Msg(false, "企业已存在，请联系管理员!");
        }
        user.setCompanyId(result);
        userService.insertUser(user);
        // 查看是否注册成功，为实体类User的id赋值
        Integer userId = userService.findUserByEmail(user.getEmail());
        if (userId != null) {
            user.setId(userId);
        } else{
            return new Msg(false, "注册用户失败");
        }
        // 注册成功后，发送账户激活链接
        user.setCreateTime(userService.queryById(user.getId()).getCreateTime());
        registerService.sendAccountActivateEmail(user);
        return new Msg(true, "注册成功，激活邮件已发送，请查收!");
    }
    /**
     * 激活
     */
    @PostMapping("/activate")
    public Msg activate(@RequestBody JSONObject requestBody) throws Exception {
        int idInt = Integer.parseInt(requestBody.getString("id"));
        // 根据用户id查找用户
        User user = userService.queryById(idInt);
        // 验证无误，状态更改为0，即激活
        String checkCode = requestBody.getString("checkCode");
        if(registerService.verifyCheckcode(user, checkCode)) {
        // 修改状态
            user.setStatus(0);
            userService.updateStatus(idInt);
            Company company = companyService.findCompanyByUser(user.getUserName());
            companyService.saveOrder(company,user);
            return new Msg(true, "激活成功!");
        }
        else
        {
            return new Msg(false, "激活已过期！");
        }
    }
    /**
     * 初始化密码
     */
    @PostMapping("/initialPassword")
    public Msg initialPassword(@RequestBody JSONObject requestBody)
            throws Exception {
        String userName = requestBody.getString("userName");
        User user = new User();
        user.setUserName(userName);
        user.setEmail(userName);
        User quser =  userService.queryUserByUserName(userName);
        if(quser == null)
        {
            return new Msg(false, "该用户不存在!");
        }
        else
        {
            if(quser.getStatus() == 1)
            {
                return new Msg(false, "请先激活该用户!");
            }
            //发送邮件
            String password = registerService.sendPasswordEmail(user);
            //修改初始化密码
            user.setPassword(Md5Util.getMd5("MD5", 0, null, password));
            user.setId(userService.findUserByEmail(user.getEmail()));
            userService.modifyUser(user);
            return new Msg(true, "初始化密码已经发送到您的邮箱，请查收!");
        }
    }
}
